<template>
  <el-dialog :title="form.id?'编辑用户':'添加用户'" :visible="dialogVisible" @close="close">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" :disabled="form.id" />
      </el-form-item>
      <el-form-item v-if="!form.id" label="密码" prop="password">
        <el-input v-model="form.password" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="电话" prop="mobile">
        <el-input v-model="form.mobile" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="send">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addUser, editUserInfo } from '@/api/UserManagement'
export default {
  name: 'Dialog',
  model: {
    prop: 'dialogVisible'
  },
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, message: '邮箱格式不正确', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          {
            pattern:
              /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号不正确',
            trigger: 'blur'
          }
        ]
      }
    }
  },

  created() {},

  methods: {
    close() {
      this.$emit('input', false)
    },
    async send() {
      await this.$refs.form.validate()
      if (this.form.id) {
        await editUserInfo(this.form)
        this.$message.success('修改成功')
      } else {
        await addUser(this.form)
        this.$message.success('添加成功')
      }
      this.$emit('success')
      this.close()
    }
  }
}
</script>

<style scoped></style>
